<?php

namespace App\Libs\Session;
use \Phalcon\DI;
use \App\Models\User\User;
class Session
{
    static $table = 't_paile_session';
    private static $prefix = 'session:';
	public $user;
    public function getUser() {
        return $this->user;
    }
	protected function __construct($user) {
		$this->user = $user;
	}


    private static function generate($uid) {
        return  md5(md5($uid . ':' . mt_rand(1, 1000)) . microtime(true));
    }
	
    /**
     * for  login regist the session
     */
    public static function regist($user) {
		$token = $user->token;
        // session
        \App\Libs\Cache\Redis::setex(self::$prefix . $token, 3600*24*30, serialize($user));

        // cookies
        $i = setcookie(SESSION_KEY, $token, time() + 7200, '/', COOKIE_DOMAIN);
        // save DB
        \App\Libs\DB\PailePdo::insert(self::$table, array(
            'uid' => $user->id,
            'token' => $token,
			'ip' => \App\Libs\Helper\Util::getIP(),
			'os' => \App\Libs\Helper\Util::getOS(),
			'version' => \App\Libs\Helper\Util::getVersion(),
            'ctime' => date('Y-m-d H:i:s'),
            'itime' => date('Y-m-d H:i:s', time() + 3600)
        ));

        return new self($user);
    }

    /**
     * for user update
     */
    public static function resetCache($user) {
		if(isset($user->token) && !empty($user->token)) {
			$key = $user->token;
		} else if (isset($_COOKIE[SESSION_KEY]) && ! empty($_COOKIE[SESSION_KEY])) {
            $key = trim($_COOKIE[SESSION_KEY]);
		} else {
			return NULL;
		}
        \App\Libs\Cache\Redis::setex(self::$prefix . $key, 3600*24*30, serialize($user) );
    }

    /**
     * for check login
     */
    public static function load() {
		// 
		$request = DI::getDefault()->get('request');
		$token = $request->get('token');
		if (isset($token) && !empty($token)) {
			$key = $token;
		} else if (isset($_COOKIE[SESSION_KEY]) && ! empty($_COOKIE[SESSION_KEY])) {
            $key = trim($_COOKIE[SESSION_KEY]);
		} else {
			return NULL;
		}
		$user = \App\Libs\Cache\Redis::get(self::$prefix . $key);
		// session expire or cache failure
		if (empty($user)) {
			$sql = 'SELECT uid FROM ' . self::$table . ' WHERE `token`=:key AND itime>:itime';
			$uid = \App\Libs\DB\PailePdo::scalar($sql, array(
					'key' => $key,
                    'itime' => date('Y-m-d H:i:s'),
            ));
			if (empty($uid)) {
				return NULL;
			}
            $user = \App\Models\User\User::find(array('id = ?0', 'bind' => array($uid)));
		} else {
			$user = unserialize($user);
		}
		return new self($user);
    }

    /**
     * for logout
     */
    public function destroy() {
        $key = $this->user->token;
        \App\Libs\Cache\Redis::delete(self::$prefix . $key);
        setcookie(SESSION_KEY, '', 0, '/', COOKIE_DOMAIN);
    }
}
